package au.com.langdale.gwt.client.remote;

import java.util.ArrayList;
/**
 * This class seeks to combine the functions of EditManager and 
 * RemoteList.<p>   
 * 
 * TODO: RemoteMutableList is under construction at this point.
 * See RemoteList and EditManager instead.
 * 
 * @author adv
 *
 */
public abstract class RemoteMutableList extends RemoteList {
	
	private ArrayList deleted = new ArrayList();
	private ArrayList inserted = new ArrayList();
	private ArrayList modified = new ArrayList();

	public void add(int ix, Object model) {
		batch.contents.add(ix, model);
		markInserted(model);
	}

	public Object remove(int ix) {
		Object result = batch.contents.remove(ix);
		markDeleted(result);
		return result; 
	}
	
	public void markInserted(Object model) {
		if( model == null || isInserted(model))
			return;
		
		inserted.add(model);
		modified.add(model);
		clients.fireModelChange(model);
	}

	public boolean isInserted(Object model) {
		return inserted.contains(model);
	}
	
	public void markModified(Object model) {
		if( model == null || isModified(model) || isDeleted(model))
			return;
		
		modified.add(model);
		clients.fireModelChange(model);
	}

	public boolean isModified(Object model) {
		return modified.contains(model);
	}

	public void markDeleted(Object model) {
		if( model == null || isDeleted(model))
			return;
		
		deleted.add(model);
		if(modified.remove(model))
			inserted.remove(model);
		clients.fireModelChange(model);
	}

	public boolean isDeleted(Object model) {
		return deleted.contains(model);
	}

	public ArrayList getDeleted() {
		return deleted;
	}

	public void save() {
		push(modified, deleted);
	}

	abstract protected void push(ArrayList modified, ArrayList deleted);
}
